#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <poll.h>

int main(void)
{	
	int fd, newfd;
	int ret;
	
	/*买电话*/
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		perror("socket");
		exit(1);
	}
	int on=1;
	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); //重用端口号 on 设置为真

	/*绑定电话卡*/
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("192.168.104.89");
	server.sin_port = htons(12001);
	ret = bind(fd, (struct sockaddr *)&server, sizeof(server));
	if (ret == -1) {
		perror("bind");
		exit(1);
	}
	
	/*监听*/
	listen(fd, 5); //不阻塞
	printf("tcp server have started...\n");

	/*接听*/
	struct sockaddr_in client; //保存对方客户端的socket地址 (来电)
	socklen_t len = sizeof(client);
	newfd = accept(fd, (struct sockaddr *)&client, &len);//没有连接请求就一直阻塞
	if (newfd == -1) {
		perror("accept");
		exit(1);
	}
	printf("connect success with client...\n");
	printf("ip:%s\n", inet_ntoa(client.sin_addr));
	printf("port:%d\n", ntohs(client.sin_port));
	system("netstat -an | grep 12001"); // 查看连接状态

	/*发送和接收*/
	struct pollfd fds[2];
	fds[0].fd = STDIN_FILENO;
	fds[0].events = POLLIN;
	fds[1].fd = newfd;
	fds[1].events = POLLIN;	
	char buf[50];
	
	while (1) 
	{
		ret = poll(fds,2,-1);
		printf("poll return:%d\n", ret);

		//键盘就绪，则输入字符串
		if (fds[0].revents & fds[0].events) 
		{
			bzero(buf, 50);
			fgets(buf, 50, stdin);
			ret = send(newfd, buf, strlen(buf), 0);
			printf("send len = %d\n", ret);
			if (strncmp(buf, "quit", 4) == 0) break;
		}
		//客户端就绪，则读取字符串
		if (fds[1].revents & fds[1].events) 
		{
			bzero(buf, 50);
			ret = read(newfd, buf, sizeof(buf)); 
			if (ret == 0) 
			{
				printf("client offline\n");
				break;
			}
			if (ret < 0) 
			{
				perror("read");
				continue;
			}
			printf("recv info: %s", buf);
			if (strncmp(buf, "quit", 4) == 0)	break;
		}
	}
	
	/*挂电话*/
	close(newfd);//先挂分机
	close(fd);//再挂主机
	
	return 0;
}

